GameLoop = function(screens){

	this.frameStartTime = 0;
	this.frameEndTime = 0;
	this.frameExecTime = 0;
	this.targetFps = 12;
	this.frameDelay = 1000 / this.targetFps;
	this.enabled = true;
	this.timeout = null;
	this.$out = $('#out');
	this.frame = 0;
	this.activeWindow = null;

	this.screens = screens;

	this.currentScreen = {
		loop : function(){}
	};

	this.loadingStates = {
		'canvas': 0
	};

	this.loop = function(){
		var tmpDate = new Date(),
			res = null;
		this.frameStartTime = (tmpDate.getSeconds()*1000)+tmpDate.getMilliseconds();
		this.frame += 1;

		res = this.currentScreen.loop();
		
		if( res !== null ) {
			
			var i = 0,
				foundLast = null,
				found = false;

			if( res == 'next' ) {
				for( i in this.screens ) {
					if( this.screens.hasOwnProperty(i) ) {
						if( found ) {
							this.setCurrentScreen(this.screens[i]);
							return;
						}
						if( this.screens[i] === this.currentScreen ) {
							found = true;
						}
					}
				}
			} else if( res == 'last' ) {

				for( i in this.screens ) {
					if( this.screens.hasOwnProperty(i) ) {
						if( this.screens[i] === this.currentScreen ) {
							this.setCurrentScreen(foundLast);
							return;
						} else {
							foundLast = this.screens[i];
						}
					}
				}

			} else if( res == 'first' ) {
				this.setCurrentScreen(this.screens[0]);
				return;
			} else if ( res == 'pause' ) {
				this.enabled = false;
				return;
			}
			
		}

		tmpDate = new Date();
		this.frameEndTime = (tmpDate.getSeconds()*1000)+tmpDate.getMilliseconds();



		if( this.frameEndTime < this.frameStartTime ) {
			this.frameStartTime -= 60000;
		}

		this.frameExecTime = this.frameEndTime - this.frameStartTime;

		if( this.frameDelay < this.frameExecTime ) {
			this.frameDelay = this.frameExecTime+1;
		} else if ( this.frameExecTime < (1000 / this.targetFps) ) {
			this.frameDelay = 1000 / this.targetFps;
		} else if ( this.frameExecTime < this.frameDelay ) {
			this.frameDelay = this.frameExecTime;
		}

		
		this.timeout = window.setTimeout(function(){
				if( this.enabled ) {
					this.loop();
				}
			}.bind(this),
		this.frameDelay);
		
	};

	this.setCurrentScreen = function(screen){
		this.enabled = false;
		this.currentScreen = screen;
		this.currentScreen.init(this);
		this.enabled = true;
		this.loop();
	};

	this.pause = function(){
		this.enabled = false;
	};

	this.start = function(){
		this.enabled = true;
		this.loop();
	};

	this.setCurrentScreen(screens[0]);

}